import React, { useEffect, useRef, useState } from 'react'
import { changeDone, delList, reviseList } from '../store/action'
import { useDispatch } from 'react-redux'
export default function TodoItem({ item }) {
  const [current, setCurrent] = useState({
    id: '',
    name: '',
  })
  const dispatch = useDispatch()
  const handleChange = (id, done) => {
    dispatch(changeDone(id, done))
  }
  const handleClick = (id) => {
    dispatch(delList(id))
  }
  const todosRef = useRef(null)
  const showEdit = ({ id, name }) => {
    setCurrent({
      name,
      id,
    })
  }
  useEffect(() => {
    todosRef.current.focus()
  }, [current])
  const handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      dispatch(reviseList(current.id, current.name))
      setCurrent({
        id: '',
        name: '',
      })
    } else if (e.keyCode === 27) {
      setCurrent({
        id: '',
        name: '',
      })
    }
  }
  return (
    <li
      className={[
        item.done ? 'completed' : '',
        item.id === current.id ? 'editing' : '',
      ].join(' ')}
      key={item.id}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.done}
          onChange={(e) => handleChange(item.id, e.target.checked)}
        />
        <label onDoubleClick={() => showEdit(item)}>{item.name}</label>
        <button className="destroy" onClick={() => handleClick(item.id)} />
      </div>
      <input
        className="edit"
        defaultValue={item.name}
        ref={todosRef}
        onBlur={() => setCurrent({ id: '' })}
        onChange={(e) => setCurrent({ ...current, name: e.target.value })}
        onKeyUp={handleKeyUp}
      />
    </li>
  )
}
